﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Tamir.IPLib.Packets;
using Tamir.IPLib;

namespace TCPSniffer
{
    public partial class MainForm : Form
    {
        private bool stop = false;

        public MainForm()
        {
            InitializeComponent();
        }

        private void obtainDevices()
        {
            /* Retrieve the device list */
            PcapDeviceList devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

            //int devices = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                //richTextBox1.AppendText(i + " " + dev.PcapDescription + "\n");
                /* Name */
                //richTextBox1.AppendText("Name: " + dev.PcapName + "\n");
                /* IP Address */
                //richTextBox1.AppendText("IP Address: " + dev.PcapIpAddress + "\n");
                /* Is Loopback */
                //richTextBox1.AppendText("Loopback: " + dev.PcapLoopback + "\n \n");

                //Extract a device from the list

                PcapDevice device = dev;

                //Open the device for capturing
                //true -- means promiscuous mode
                //1000 -- means a read wait of 1000ms

                device.PcapOpen(true, 1000);

                richTextBox1.AppendText("-- Listenning on " + device.PcapDescription);

                Packet packet = null;

                //Keep capture packets using PcapGetNextPacket()

                while (true)
                {
                    // Prints the time and length of each received packet

                    packet = device.PcapGetNextPacket();
                    DateTime time = packet.PcapHeader.Date;
                    int len = packet.PcapHeader.PacketLength;
                    Console.WriteLine("{0}:{1}:{2},{3} Len={4}",
                              time.Hour, time.Minute, time.Second,
                              time.Millisecond, len);
                }
                //Close the pcap device

                device.PcapClose();
                richTextBox1.AppendText("-- Capture stopped, device closed.");
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            obtainDevices();
        }
    }
}
